import { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { message, Spin } from 'antd';
import api from '../../api';

export default function Callback() {
    const [loading, setLoading] = useState(true);
    const navigate = useNavigate();
    const location = useLocation();

    useEffect(() => {
        const searchParams = new URLSearchParams(location.search);
        const code = searchParams.get('code');
        const state = searchParams.get('state');

        if (!code) {
            message.error('授权失败，未获取到授权码');
            return;
        }

        const handleCallback = async () => {
            try {
                const response = await api.get(`/gitee/callback?code=${code}&state=${state}`);
                const { token, refreshToken, user } = response.data;
                const  username:any  = [user];
                // 存储token和用户信息
                localStorage.setItem('token', token);
                localStorage.setItem('refreshToken', refreshToken);
                localStorage.setItem('user', JSON.stringify(username));
               
                navigate('/CXF');
            } catch (error) {
                
            } finally {
                setLoading(false);
            }
        };

        handleCallback();
    }, [navigate, location]);

    if (loading) {
        return (
            <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '100vh' 
            }}>
                <Spin size="large" tip="正在处理登录..." />
            </div>
        );
    }

    return null;
}